<?php
/*

  Copyright (c) 2008   by  maxim.oransky <maxim.oransky@gmail.com>,
  auhtor of  the-wheel-library  team

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

class Autoloader {

    const EXT = 'php';

    private static $hClasses = array();

    private static function init() {

        if (function_exists('__autoload')) return;

        function __autoload($className) {

            //echo "=$className=";
            $path = Autoloader::getFilePathByClassName($className);

            if (!$path)
                throw new Exception('Can not find class "' . $className . '"');

            require_once $path;
        }
    }


    public static function addFolders(array $arrFolders) {

        self::init();

        foreach($arrFolders as $dirPath) {

            foreach (Dir::getFiles($dirPath, '*.' . self::EXT) as $filePath) {

                if (preg_match('~([^./\\\\]*)\.' . self::EXT .'$~', $filePath, $m)) {
                    $className = $m[1];
                    self::$hClasses[$className] = $filePath;
                }
            }
        }
    }

    public static function addFolder($dirPath) {
        self::addFolders(array($dirPath));
    }

    public static function getFilePathByClassName($className) {
        return isset(self::$hClasses[$className]) ?
            self::$hClasses[$className] :
            false;
    }
}

?>
